package com.carkeeper.oauth.controller;

import com.carkeeper.entity.Result;
import com.carkeeper.entity.StatusCode;
import com.carkeeper.oauth.service.AuthService;
import com.carkeeper.oauth.util.AuthToken;
import com.carkeeper.oauth.util.CookieUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Controller
@RequestMapping("/oauth")
public class AuthController {
    @Autowired
    private AuthService authService;

    @Value("${auth.clientId}")
    private String clientId;

    @Value("${auth.clientSecret}")
    private String clientSecret;

    @Value("${auth.cookieDomain}")
    private String cookieDomain;

    @Value("${auth.cookieMaxAge}")
    private Integer cookieMaxAge;

    @PostMapping("/login")
    @ResponseBody
    public Result login(@RequestBody Map<String,String> map, HttpServletResponse response){

        String username = map.get("username");
        String password = map.get("password");

        if (StringUtils.isEmpty(username)){
            throw new RuntimeException("请输入用户名");
        }
        if (StringUtils.isEmpty(password)){
            throw new RuntimeException("请输入密码");
        }
        AuthToken authToken = authService.login(username, password, clientId, clientSecret);
        this.saveJtiToCookie(authToken,response);
        return new Result(true, StatusCode.OK,"登陆成功");
    }

    public void saveJtiToCookie(AuthToken authToken, HttpServletResponse response){
        CookieUtil.addCookie(response,cookieDomain,"/","Admin-Token",authToken.getAccessToken(),cookieMaxAge,false);
        CookieUtil.addCookie(response,cookieDomain,"/","uid",authToken.getJti(),cookieMaxAge,false);
    }

    @GetMapping("/toLogin")
    public String toLogin(@RequestParam(name = "FROM",defaultValue = "",required = false)String from, Model model){
        model.addAttribute("from",from);
        return "login";
    }

}
